<template>
  <div class="home-left-category-nav relative bg-white h-[460px] w-[240px] shadow rounded">
    <!-- Loading State -->
    <div v-if="isLoading" class="p-4">
      <div class="animate-pulse space-y-2">
        <div v-for="i in 5" :key="i" class="h-6 bg-gray-200 rounded"></div>
      </div>
    </div>

    <!-- Category List -->
    <ul v-else class="category-list p-4 space-y-1">
      <li
        v-for="(category, index) in categoryData"
        :key="category.id"
        class="category-item p-2 hover:bg-gray-100 rounded cursor-pointer flex justify-between items-center text-sm"
        @mouseenter="showPanel(index)"
        @mouseleave="hidePanelWithDelay"
      >
        <div class="flex items-center">
          <img
            v-if="category.pic"
            :src="category.pic"
            :alt="category.name"
            class="w-4 h-4 mr-2 object-contain"
          />
          <span>{{ category.name }}</span>
        </div>
        <el-icon><ArrowRight /></el-icon>
      </li>
    </ul>

    <!-- Popup Panel -->
    <transition name="fade">
      <div
        v-show="activePanelIndex !== null && currentPanelData"
        class="category-panel absolute left-full top-0 w-[960px] h-full bg-gradient-to-br from-teal-50 via-emerald-50 to-green-50 shadow-lg rounded-r border border-l-0 border-gray-200 z-50 p-6 overflow-y-auto"
        @mouseenter="cancelHidePanel"
        @mouseleave="startHidePanel"
      >
        <div v-if="currentPanelData" class="flex gap-6">
          <!-- Sub Categories -->
          <div class="sub-categories w-2/3">
            <div class="flex flex-wrap gap-3">
              <router-link
                v-for="subGroup in currentPanelData.subCategories"
                :key="subGroup.id"
                :to="`/products?category=${subGroup.id}`"
                class="group flex items-center px-3 py-1.5 rounded-lg bg-gradient-to-br from-teal-600 via-emerald-500 to-green-500 hover:from-teal-700 hover:via-emerald-600 hover:to-green-600 transition-all duration-300 shadow-sm hover:shadow-md"
              >
                <img
                  v-if="subGroup.pic"
                  :src="subGroup.pic"
                  :alt="subGroup.title"
                  class="w-4 h-4 mr-2 object-contain opacity-90 group-hover:opacity-100 transition-opacity brightness-0 invert"
                />
                <span class="text-sm text-white group-hover:text-white/90 transition-colors font-medium">{{ subGroup.title }}</span>
              </router-link>
            </div>
          </div>
          <!-- Brands -->
          <div v-if="currentPanelData.brands.length" class="brands w-1/3">
            <h4 class="font-semibold text-gray-800 mb-3 text-sm">推荐品牌</h4>
            <div class="grid grid-cols-2 gap-2">
              <a
                v-for="brand in currentPanelData.brands"
                :key="brand.name"
                :href="brand.link"
                class="brand-item border rounded hover:shadow-sm transition-shadow flex items-center justify-center p-1 h-12"
              >
                <img :src="brand.logoUrl" :alt="brand.name" class="max-h-8 max-w-full object-contain">
              </a>
            </div>
          </div>
        </div>
        <!-- Empty State -->
        <div v-else class="text-center text-gray-500 p-10">暂无数据</div>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ArrowRight } from '@element-plus/icons-vue'
import { goodsApi } from '@/api'
import type { GoodsType } from '@/api/modules/goods'

// --- Interfaces ---
interface SubCategoryItem { 
  id: number
  name: string
  pic: string | null
  link: string
}

interface SubCategoryGroup { 
  id: number
  title: string
  pic: string | null
  items: SubCategoryItem[]
}

interface CategoryPanelData {
  subCategories: SubCategoryGroup[]
  brands: BrandItem[]
}

interface BrandItem { 
  name: string
  logoUrl: string
  link?: string
}

interface TopLevelCategory { 
  id: number
  name: string
  pic: string | null
  panelData: CategoryPanelData
}

// --- Data ---
const categoryData = ref<TopLevelCategory[]>([])
const isLoading = ref(true)

// 获取商品类型数据
const fetchGoodsTypes = async () => {
  try {
    const res: any = await goodsApi.getGoodsTypeList({
      sort: 'asc',
      order: 'sortNum'
    })
    if (res.code === 1000 && res.data) {
      // 处理数据，构建层级结构
      const types = res.data // 直接使用返回的数组数据
      const topLevelTypes = types
        .filter((type: GoodsType) => type.parentId === null)
        .sort((a: GoodsType, b: GoodsType) => a.sortNum - b.sortNum)
      
      categoryData.value = topLevelTypes.map((topType: GoodsType) => {
        // 获取当前顶级分类下的子分类，并按 sortNum 排序
        const subTypes = types
          .filter((type: GoodsType) => type.parentId === topType.id)
          .sort((a: GoodsType, b: GoodsType) => a.sortNum - b.sortNum)
        
        return {
          id: topType.id,
          name: topType.name,
          pic: topType.pic,
          panelData: {
            subCategories: subTypes.map((subType: GoodsType) => ({
              id: subType.id,
              title: subType.name,
              pic: subType.pic,
              items: [{
                id: subType.id,
                name: subType.name,
                pic: subType.pic,
                link: `/goods?type=${subType.id}`
              }]
            })),
            brands: [] // 品牌数据可以后续添加
          }
        }
      })
    }
  } catch (error) {
    console.error('获取商品类型失败:', error)
  } finally {
    isLoading.value = false
  }
}

// --- Panel Logic ---
const activePanelIndex = ref<number | null>(null)
const hidePanelTimer = ref<NodeJS.Timeout | null>(null)

const currentPanelData = computed(() => {
  return activePanelIndex.value !== null ? categoryData.value[activePanelIndex.value]?.panelData : null
})

function showPanel(index: number) {
  cancelHidePanel()
  activePanelIndex.value = index
}

function hidePanelWithDelay() {
  hidePanelTimer.value = setTimeout(() => { activePanelIndex.value = null }, 200)
}

function cancelHidePanel() {
  if (hidePanelTimer.value) {
    clearTimeout(hidePanelTimer.value)
    hidePanelTimer.value = null
  }
}

function startHidePanel() {
  hidePanelWithDelay()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchGoodsTypes()
})
</script>

<style scoped>
.category-panel {
  /* Positioned to the right of the nav */
  box-shadow: 2px 0 5px rgba(0,0,0,0.1);
  border-radius: 0 0.5rem 0.5rem 0; /* Adjust rounding */
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.2s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style> 